package org.example.fastproject.core.exception;

import cn.hutool.http.HttpStatus;
import lombok.extern.slf4j.Slf4j;
import org.example.fastproject.core.bean.ViewResult;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Author 王海舟
 * @Date 2023/1/3 15:40
 * @PackageName:org.example.store.common.exception
 * @ClassName: GlobalExceptionHandler
 * @Description: 全局异常处理器
 * @Version 1.0
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 请求接口异常处理
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = ApiException.class)
    public ViewResult handle(ApiException e) {
        return ViewResult.error(e.getMessage());
    }

    /**
     * 请求方法参数错误
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ViewResult handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String message = null;
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                message = fieldError.getField()+fieldError.getDefaultMessage();
            }
        }
        return ViewResult.error(HttpStatus.HTTP_BAD_REQUEST,message);
    }

    /**
     * 请求接口不存在
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = BindException.class)
    public ViewResult handleValidException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        String message = null;
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                message = fieldError.getField()+fieldError.getDefaultMessage();
            }
        }
        return ViewResult.error(HttpStatus.HTTP_NOT_FOUND,message);
    }

    /**
     * 访问被拒绝
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = AccessDeniedException.class)
    public ViewResult handleAccessDeniedException(AccessDeniedException e){
        return ViewResult.error(HttpStatus.HTTP_FORBIDDEN,e.getMessage());
    }

    /**
     * 通用异常处理
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public ViewResult handleException(Exception e){
        e.printStackTrace();
        return ViewResult.error("系统错误: " + e.getMessage());
    }
}